package com.example.serviceheadlines.service.impl;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.serviceheadlines.mapper.HeadlinesCommentMapper;
import com.example.serviceheadlines.service.HeadlinesService;
import com.example.serviceheadlines.service.IHeadlinesCommentService;
import com.example.serviceheadlines.service.IHeadlinesThumpService;
import com.github.pagehelper.PageHelper;
import com.tangyuan.common.result.Result;
import com.tangyuan.common.result.ResultCodeEnum;
import com.tangyuan.common.util.CollUtils;
import com.tangyuan.common.util.DateUtil;
import com.tangyuan.dto.HeadlinesCommentDto;
import com.tangyuan.model.Headlines;
import com.tangyuan.model.HeadlinesComment;
import com.tangyuan.model.HeadlinesThump;
import com.tangyuan.model.User;
import com.tangyuan.vo.HeadLinesCommentCountVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: headlines_comment
 * @Author: jeecg-boot
 * @Date: 2024-03-18
 * @Version: V1.0
 */
@Service
public class HeadlinesCommentServiceImpl extends ServiceImpl<HeadlinesCommentMapper, HeadlinesComment> implements IHeadlinesCommentService {

    @Autowired
    private HeadlinesService headlinesService;

    @Autowired
    private HeadlinesCommentMapper headlinesCommentMapper;

    /**
     * 百家评论及回复评论
     *
     * @return
     */
    @Override
    public Result addComment(User user, HeadlinesCommentDto headlinesCommentDto) {
        Headlines headlines = headlinesService.getById(headlinesCommentDto.getHeadlinesId());
        if(headlines == null){
            return Result.build(null, ResultCodeEnum.DATA_ERROR);
        }
        HeadlinesComment headlinesComment = BeanUtil.copyProperties(headlinesCommentDto, HeadlinesComment.class);
        //添加创建时间
        Long round = Math.round(Double.valueOf( DateUtil.changeLocalDateTimeToDate(LocalDateTime.now()).getTime())/1000);
        headlinesComment.setCreateBy(round);
        headlinesComment.setCreateTime(new Date());
        headlinesComment.setUserId(user.getId());
        headlinesComment.setHeadlinesId(headlinesCommentDto.getHeadlinesId());
        headlinesComment.setUserIcon(user.getHeadImage());
        headlinesComment.setUserName(user.getName());
        headlinesComment.setArea(user.getProvince());

        if (headlinesCommentDto.getParentId() != null && headlinesCommentDto.getParentId() != 0) {
            HeadlinesComment comment = this.getById(headlinesCommentDto.getParentId());
            if (comment.getReplyId() != null && comment.getReplyId() != 0) {
                headlinesComment.setReplyId(comment.getReplyId());
            } else {
                headlinesComment.setReplyId(comment.getId());
            }
        } else {
            headlinesComment.setReplyId(0L);
            headlinesComment.setParentId(0L);
        }
        this.save(headlinesComment);


        headlines.setArea(user.getProvince());

        headlines.setCommentNum(headlines.getCommentNum() + 1);
        headlinesService.updateById(headlines);
        return Result.ok(headlinesComment);
    }

    @Override
    public Result<Object> selectCommentByHeadlinesId(User user, HeadlinesComment headlinesComment, Integer pageSize, Integer pageNum) {
        PageHelper.startPage(pageNum, pageSize);
        //分页查询一级评论
        List<HeadlinesComment> list = headlinesCommentMapper.findHeadlinesOneComment(headlinesComment);
        HeadLinesCommentCountVo countVo = new HeadLinesCommentCountVo();
        countVo.setCommentCount(headlinesCommentMapper.findHeadlinesCommentCount(headlinesComment));
        if(CollUtils.isEmpty(list)){
            return Result.ok(countVo);
        }
        //查询分页之后评论的二级评论
        List<HeadlinesComment> twoList = headlinesCommentMapper.findHeadlinesTwoComment(list.stream().map(HeadlinesComment::getId).collect(Collectors.toList()),headlinesComment.getHeadlinesId());
        list.addAll(twoList);
        //查看该登录用户是否对评论点赞或设置不喜欢
        if(user != null){
            List<Long> commentIds = list.stream().map(HeadlinesComment::getId).collect(Collectors.toList());
            List<HeadlinesThump> thumpList = headlinesCommentMapper.findCommentThump(user.getId(),commentIds);
            if(!CollUtils.isEmpty(thumpList)){
                Map<Long, List<HeadlinesThump>> collected = thumpList.stream().collect(Collectors.groupingBy(HeadlinesThump::getAId));
                list.forEach(comment ->{
                    List<HeadlinesThump> thumps = collected.get(comment.getId());
                    if(!CollUtils.isEmpty(thumps)){
                        thumps.forEach(thump ->{
                            if(thump.getIsLike() == 0){
                                comment.setIsLike(1);
                            } else if (thump.getIsLike() == 1){
                                comment.setIsDisLike(1);
                            }
                        });
                    }
                });
            }
        }
        //一级评论
        List<HeadlinesComment> oneCommons = list.stream().filter(comment -> comment.getParentId().equals(0L)).collect(Collectors.toList());
        //二级评论
        List<HeadlinesComment> twoCommons = list.stream().filter(comment -> !comment.getParentId().equals(0L)).collect(Collectors.toList());
        //一级评论赋值
        if(!CollUtils.isEmpty(twoCommons)){
            for (HeadlinesComment one : oneCommons) {
                List<HeadlinesComment> twoCommon = twoCommons.stream().filter(vo -> vo.getReplyId().equals(one.getId())).collect(Collectors.toList());
                if(!CollUtils.isEmpty(twoCommon)){
                    Map<Long, String> map = twoCommon.stream().collect(Collectors.toMap(HeadlinesComment::getId,HeadlinesComment::getUserName,(h1,h2)->h1));
                    for (HeadlinesComment comment : twoCommon) {
                        //如果ParentId和ReplyId不一致,则证明该条评论是在回复二级评论,设置parentName(被回复人用户名)
                        if(!comment.getParentId().equals(comment.getReplyId())){
                            comment.setParentName(map.get(comment.getParentId()));
                        }
                    }
                }
                one.setComments(twoCommon);
            }
        }
        countVo.setCommentVos(oneCommons);
        return Result.ok(countVo);
    }

    @Override
    public void updateHeadlinesCommentName(String nickName, Long userId) {
        headlinesCommentMapper.updateHeadlinesCommentName(nickName,userId);
    }

    @Override
    public void updateHeadlinesCommentAvatar(String url, Long userId) {
        headlinesCommentMapper.updateHeadlinesCommentAvatar(url,userId);
    }
}
